package com.sobot.finance.poc.web.util;

import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.google.common.base.Charsets;
import com.sobot.finance.poc.web.config.SysConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 短信客户端
 *
 * @author baiyp
 */
@Slf4j
@Component
public class SmsClient {

    @Resource
    private SysConfig sysConfig;
    /**
     * 默认类型
     */
    private static final String CONTENT_TYPE = "application/json;charset=utf-8";

    /**
     * 超时时间：毫秒
     */
    private static final int TIME_OUT = 60_000;

    /**
     * 成功返回
     */
    private static final String SUCCESS = "OK";

    public boolean sendSms(String phone, String msg) {
        log.info("[发送短信-开始]: {} {}", phone, msg);
        boolean success = false;
        if (StrUtil.hasEmpty(phone, msg)) {
            return false;
        }
        try {
            // 是用临时模板
            String msgTemporaryTemplate = sysConfig.getMsgTemporaryTemplate();
            String smsMsg = URLEncodeUtil.encode(msgTemporaryTemplate, Charsets.UTF_8);
            String smsUrl = StrUtil.format(sysConfig.getSmsUrl(), sysConfig.getSmsName(),
                    sysConfig.getSmsPwd(), phone, msg);
            try {
                // 控制发送频率
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
            }
            // 请求
            String result = HttpRequest.get(smsUrl)
                    .header(Header.CONTENT_TYPE, CONTENT_TYPE)
                    .timeout(TIME_OUT)
                    .execute()
                    .body();
            log.info("[result]: {}", result);
            if (Objects.nonNull(result) && result.contains(SUCCESS)) {
                success = true;
            }
        } catch (Exception e) {
            log.error("[异常]: ", e);
        }
        log.info("[发送短信-结束]: {}", success);
        return success;
    }

    public static boolean isNotNull(String s) {
        if (null == s) {
            return false;
        }
        if (s.trim().equals("null")) {
            return false;
        }
        if (s.trim().equals("")) {
            return false;
        }
        if (s.trim().length() == 0) {
            return false;
        }
        return true;
    }
}
